from pydantic import BaseModel, Field, validator
from typing import Optional, List, Dict, Any
from datetime import datetime


class AgentBase(BaseModel):
    """智能体基础模型"""
    name: str = Field(..., min_length=2, max_length=64, description="智能体名称")
    description: Optional[str] = Field(None, description="智能体描述")
    avatar: Optional[str] = Field(None, description="智能体头像URL")
    category: Optional[str] = Field(None, max_length=64, description="智能体分类")
    agent_type: str = Field(..., max_length=32, description="智能体类型（内嵌型、外链型）")
    status: str = Field("active", max_length=32, description="智能体状态")
    version: str = Field("1.0.0", max_length=16, description="版本号")
    config: Optional[Dict[str, Any]] = Field(None, description="智能体配置")
    department_id: Optional[str] = Field(None, description="部门ID")

    @validator('department_id', pre=True)
    def validate_department_id(cls, v):
        """验证部门ID，将空字符串转换为None"""
        if v == "" or v is None:
            return None
        return str(v) if v is not None else None

    @validator('status')
    def validate_status(cls, v):
        """验证状态值"""
        allowed_statuses = ['active', 'inactive', 'deleted']
        if v not in allowed_statuses:
            raise ValueError(f'状态必须是以下值之一: {allowed_statuses}')
        return v

    @validator('agent_type')
    def validate_agent_type(cls, v):
        """验证智能体类型"""
        allowed_types = ['内嵌型', '外链型']
        if v not in allowed_types:
            raise ValueError(f'智能体类型必须是以下值之一: {allowed_types}')
        return v


class AgentCreate(AgentBase):
    """创建智能体请求模型"""
    pass


class AgentUpdate(BaseModel):
    """更新智能体请求模型"""
    name: Optional[str] = Field(None, min_length=2, max_length=64, description="智能体名称")
    description: Optional[str] = Field(None, description="智能体描述")
    avatar: Optional[str] = Field(None, description="智能体头像URL")
    category: Optional[str] = Field(None, max_length=64, description="智能体分类")
    agent_type: Optional[str] = Field(None, max_length=32, description="智能体类型（内嵌型、外链型）")
    status: Optional[str] = Field(None, max_length=32, description="智能体状态")
    version: Optional[str] = Field(None, max_length=16, description="版本号")
    config: Optional[Dict[str, Any]] = Field(None, description="智能体配置")
    department_id: Optional[str] = Field(None, description="部门ID")

    @validator('department_id', pre=True)
    def validate_department_id(cls, v):
        """验证部门ID，将空字符串转换为None"""
        if v == "" or v is None:
            return None
        return str(v) if v is not None else None

    @validator('status')
    def validate_status(cls, v):
        """验证状态值"""
        if v is not None:
            allowed_statuses = ['active', 'inactive', 'deleted']
            if v not in allowed_statuses:
                raise ValueError(f'状态必须是以下值之一: {allowed_statuses}')
        return v

    @validator('agent_type')
    def validate_agent_type(cls, v):
        """验证智能体类型"""
        if v is not None:
            allowed_types = ['内嵌型', '外链型']
            if v not in allowed_types:
                raise ValueError(f'智能体类型必须是以下值之一: {allowed_types}')
        return v


class AgentOut(BaseModel):
    """智能体输出模型"""
    id: int
    name: str
    description: Optional[str] = None
    avatar: Optional[str] = None
    category: Optional[str] = None
    agent_type: str
    status: str
    version: str = "1.0.0"
    config: Optional[Dict[str, Any]] = None
    created_by_id: Optional[int] = None
    created_by_name: Optional[str] = None
    department_id: Optional[str] = None
    department_name: Optional[str] = None
    created_at: Optional[str] = None
    updated_at: Optional[str] = None

    class Config:
        from_attributes = True


class AgentList(BaseModel):
    """智能体列表响应模型"""
    items: List[AgentOut]
    total: int
    page: int = 1
    limit: int = 10

    class Config:
        from_attributes = True


class PaginationParams(BaseModel):
    """分页参数模型"""
    page: int = Field(1, ge=1, description="页码")
    limit: int = Field(10, ge=1, le=100, description="每页数量")
    search: Optional[str] = Field(None, description="搜索关键词")
    agent_type: Optional[str] = Field(None, description="智能体类型")
    category: Optional[str] = Field(None, description="智能体分类")
    status: Optional[str] = Field(None, description="智能体状态")
    department_id: Optional[str] = Field(None, description="部门ID")
    include_deleted: bool = Field(False, description="是否包含已删除的记录")




class AgentSearchRequest(BaseModel):
    """智能体搜索请求模型"""
    keyword: str = Field(..., min_length=1, description="搜索关键词")
    limit: int = Field(10, ge=1, le=50, description="返回数量限制")
    category: Optional[str] = Field(None, description="分类筛选")
    agent_type: Optional[str] = Field(None, description="类型筛选")


class AgentCopyRequest(BaseModel):
    """智能体复制请求模型"""
    name: Optional[str] = Field(None, min_length=2, max_length=64, description="新智能体名称")
    description: Optional[str] = Field(None, description="新智能体描述")
    category: Optional[str] = Field(None, max_length=64, description="新智能体分类")
    department_id: Optional[str] = Field(None, description="目标部门ID")


class AgentExportConfig(BaseModel):
    """智能体导出配置模型"""
    id: int
    name: str
    description: Optional[str] = None
    avatar: Optional[str] = None
    category: Optional[str] = None
    agent_type: str
    config: Optional[Dict[str, Any]] = None
    version: str = "1.0.0"
    export_time: str
    exported_by: str

    class Config:
        from_attributes = True


class AgentImportConfig(BaseModel):
    """智能体导入配置模型"""
    name: str = Field(..., min_length=2, max_length=64, description="智能体名称")
    description: Optional[str] = Field(None, description="智能体描述")
    avatar: Optional[str] = Field(None, max_length=255, description="智能体头像URL")
    category: Optional[str] = Field(None, max_length=64, description="智能体分类")
    agent_type: str = Field(..., max_length=32, description="智能体类型")
    config: Optional[Dict[str, Any]] = Field(None, description="智能体配置")
    department_id: Optional[str] = Field(None, description="部门ID")

    @validator('department_id', pre=True)
    def validate_department_id(cls, v):
        """验证部门ID，将空字符串转换为None"""
        if v == "" or v is None:
            return None
        return str(v) if v is not None else None

    @validator('agent_type')
    def validate_agent_type(cls, v):
        """验证智能体类型"""
        allowed_types = ['内嵌型', '外链型']
        if v not in allowed_types:
            raise ValueError(f'智能体类型必须是以下值之一: {allowed_types}')
        return v
